package viz.view.mediators
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	
	import viz.model.flare.data.StateItem;
	import viz.view.forms.CreateStateForm;

	public class CreateStateFormMediator extends Mediator
	{
		public static const NAME:String = "AddStateMediator";
		
		// outgoing notes
		public static const CREATE_STATE_FORM_ADD:String = "createStateForm/addState";
		public static const CREATE_STATE_FORM_READY:String = "createStateForm/ready";
		
		//todo: this should me moved to preferances
		private static const PACKAGE_DELIMETER:String = ".";
		
		private var isCreated:Boolean;
		
		public function CreateStateFormMediator( )	{
			super(NAME, new CreateStateForm());
			initMediator( );
		}
		
		override public function onRegister():void{
			sendNotification( CREATE_STATE_FORM_READY, view );
		}
		
		private function initMediator( ):void{
			view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
		}

		/* public function set packageList(list:ArrayCollection):void{
			view.pkgCombo.sharedDataProvider = list;
		} */
		
		private function onCreationComplete(event:FlexEvent):void{
			view.removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			view.addEventListener(Event.REMOVED, onRemoved);
			isCreated = true;
			activate();
		}
		
		private function onRemoved(event:Event):void{
			if(event.target != view)return;
			view.removeEventListener(Event.REMOVED, onRemoved);
			deactivate();
			setViewComponent( null );
			facade.removeMediator( mediatorName );
		}
		
		public function activate():void{
			view.pkgCombo.setFocus();
			addListeners();
		}
		
		public function deactivate():void{
			removeListeners();
			view.pkgCombo.commit();
		}
		
		private function addListeners():void{
			view.input.addEventListener(FlexEvent.ENTER, onCommit);
		}
		
		private function removeListeners():void{
			view.removeEventListener(FlexEvent.ENTER, onCommit);
		}
		
		private function onCommit( event:Event ):void{
			sendCreateStateNote();
			view.input.text = "";
		}
		
		private function sendCreateStateNote():void{
			var state:StateItem = new StateItem()
			state.fullPath = view.pkgCombo.text + PACKAGE_DELIMETER + view.input.text
			view.pkgCombo.commit();
			sendNotification( CREATE_STATE_FORM_ADD, state )
		}
		
		private function get view():CreateStateForm{
			return CreateStateForm(viewComponent);
		}
		
	}
}